interface ApiConfig {
    api: (...args: any[]) => Promise<any>;
    params?: Object;
    pageSize: string;
    pageNumber: string;
    formatResults: (data: any) => [any, number];
}
export const useTable = (apiConfig: ApiConfig, options?: { defaultPageSize?: number; isPagination: boolean }) => {
    const defaultPageSize = options?.defaultPageSize ?? 10;
    const { api, pageSize: sizePropName, pageNumber: numberPropName, formatResults } = apiConfig;
    const { pageSize, pageNumber, total, setTotal, changeNumberAndSize } = usePagination(() => getTableData(), {
        defaultPageSize
    });
    const loading = ref(true);
    const tableData = ref<any>([]);
    const getTableData = async () => {
        try {
            loading.value = true;
            let apiParams: any = {};
            if (options?.isPagination) {
                apiParams = {
                    [sizePropName]: pageSize.value,
                    [numberPropName]: pageNumber.value
                };
            }
            if (apiConfig.params) {
                apiParams = {
                    ...apiConfig.params,
                    ...apiParams
                };
            }
            const res = await api(apiParams);
            const [data, totalCount] = formatResults ? formatResults(res) : [res, 0];
            setTotal(totalCount);
            tableData.value = data;
            loading.value = false;
        } catch (err) {
            loading.value = false;
            console.error('表格数据请求出错啦！！！', err);
        }
    };
    return { tableData, loading, pageSize, pageNumber, total, changeNumberAndSize, getTableData };
};
interface PaginationOptions {
    defaultPageSize: number;
}
export const usePagination = (callback: () => void, paginationOptions: PaginationOptions) => {
    const { defaultPageSize } = paginationOptions;
    const pagination = reactive({
        pageSize: defaultPageSize || 10,
        pageNumber: 1,
        total: 0,
        change: (pageNumber: number, pageSize: number) => {
            pagination.pageNumber = pageNumber;
            pagination.pageSize = pageSize;
            callback();
        }
    });
    const setTotal = (total: number) => {
        pagination.total = total;
    };
    const changeNumberAndSize = pagination.change;
    const { pageSize, pageNumber, total } = toRefs(pagination);
    return { pageSize, pageNumber, total, setTotal, changeNumberAndSize };
};
